package org.fast.develop.logicflow.runtime.ws;

import cn.hutool.json.JSONUtil;
import org.fast.develop.logicflow.runtime.enums.WebsocketStatusEnum;
import org.fast.develop.logicflow.runtime.instance.LogicFlowInstance;

import java.io.IOException;

/**
 * @author czh
 * @version V1.0
 * @data Created on 2023-01-29 17:01
 */
public class LogicFlowEventPublisher {

    private static IWebSocketLauncher webSocketLauncher;

    public LogicFlowEventPublisher(IWebSocketLauncher webSocketLauncher) {
        this.webSocketLauncher = webSocketLauncher;
    }

    public static void sendMsg(WebsocketStatusEnum status, String sessionId, LogicFlowInstance logicFlowInstance, String activeId) throws IOException {
        ResultMessage resultMessage = new ResultMessage(status);
        if (WebsocketStatusEnum.STATUS_500.equals(status)) {
            resultMessage.setError(new ResultError("500", logicFlowInstance.getLogicFlowMonitor().getExceptionMsg()));
        }

        resultMessage.setData(
                new ResultData()
                        .setExecutionIds(logicFlowInstance.getLogicFlowMonitor().getExecuteIds())
                        .setResult(logicFlowInstance.getVariables())
                        .setLogsObj(logicFlowInstance.getLogicFlowMonitor().getExecuteLogs())
                        .setActiveId(activeId)
        );
        webSocketLauncher.sendMsg(sessionId, JSONUtil.toJsonStr(resultMessage));
    }

    public static void close(String sessionId) {
        // 中断连接
        webSocketLauncher.getSessionStore().removeAndClose(sessionId);
    }
}
